import { getMenuDetailApi } from "@/apis/menu";
import { defineStore } from "pinia";
import type { RouteRecordRaw } from "vue-router";
import Layout from "@/layout/index.vue";
const modules = import.meta.glob("../../views/**/*.vue");
import center from "@/layout/center/center.vue";
export const menuStore = defineStore("menuStore", {
  state: () => {
    return {
      collapse: false,
      menuList: [
        {
          path: "/dashboard",
          component: "Layout",
          name: "dashboard",
          meta: {
            title: "首页",
            icon: "HomeFilled",
            roles: ["sys:dashboard"],
          },
        },
      ],
    };
  },
  getters: {
    getCollapse(state) {
      return state.collapse;
    },
    getMenu(state) {
      return state.menuList;
    },
  },
  actions: {
    setCollapse(collapse: boolean) {
      this.collapse = collapse;
    },
    getMenuList(router: any, userId: string) {
      return new Promise((resolve, reject) => {
        getMenuDetailApi(userId)
          .then((res: any) => {
            let accessRoute;
            if (res && res.code == 200) {
              accessRoute = generateRoute(res.data, router) as any;
              this.menuList = this.menuList.concat(accessRoute);
            }
            console.log(this.menuList, 242424);
            resolve(this.menuList);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
});
export function generateRoute(routes: RouteRecordRaw[], router: any) {
  const res: Array<RouteRecordRaw> = [];
  routes.forEach((route: any) => {
    const tmp = { ...route };
    const component = tmp.component;
    if (route.component) {
      if (component === "Layout") {
        tmp.component = Layout;
      } else {
        console.log(tmp.component, 11111);
        tmp.component = modules[`../../${component}`];
        console.log(tmp.component, 22222);
      }
    }
    if (tmp.children && tmp.children.length > 0) {
      if (route.component !== "Layout") {
        tmp.children = center;
      }
      tmp.children = generateRoute(tmp.children, router);
    }
    res.push(tmp);
    router.addRoute(tmp);
  });
  return res;
}
